package com.sx.zongzhi.net;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.sx.zongzhi.MyApplication;
import com.sx.zongzhi.utils.BaseUtil;
import com.sx.zongzhi.utils.Global;
import com.sx.zongzhi.utils.NetworkUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.CacheControl;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @version V1.0
 * @description: ${}(用一句话描述该文件做什么)
 */
public class ServiceFactory {

    public static String OLD_API_BASE_URL = "";//测试路径
//    public static String NEW_API_BASE_URL = "http://delingha-zztest.orgid.xyz";
//    public static String NEW_API_BASE_URL = "http://123.206.109.82:8081";
    public static String NEW_API_BASE_URL = "http://delingha-zztest.hzsxkj.cn";
    private static  ServiceFactory serviceFactory;

//    //定义一个信任所有证书的TrustManager
//    private static X509TrustManager trustAllCert = new X509TrustManager() {
//        @Override
//        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
//        }
//
//        @Override
//        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
//        }
//
//        @Override
//        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
//            return new java.security.cert.X509Certificate[]{};
//        }
//    };


    public synchronized static ServiceFactory getInstance(){
        if(serviceFactory == null){
            serviceFactory = new ServiceFactory();
        }
        return serviceFactory;
    }



    private final OkHttpClient sHttpClient = new OkHttpClient.Builder()
            //  .sslSocketFactory(new Tls12SocketFactory(trustAllCert), trustAllCert)
            .addInterceptor(new MyInterceptor())
            .retryOnConnectionFailure(true)//连接失败后是否重新连接
            .connectTimeout(10, TimeUnit.SECONDS)//超时时间10S
//            .cache(getCache())//设置缓存目录
//            .addInterceptor(cacheInterceptor())
//            .addNetworkInterceptor(cacheInterceptor())
            .build();



    //缓存拦截器
    private Interceptor cacheInterceptor() {
        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();

                if (NetworkUtils.getNetWorkState(MyApplication.context)== Global.NETWORK_NONE) {
                    request = request.newBuilder()
                            //强制使用缓存
                            .cacheControl(CacheControl.FORCE_CACHE)
                            .build();
                }

                Response response = chain.proceed(request);

                if (NetworkUtils.getNetWorkState(MyApplication.context)!= Global.NETWORK_NONE) {
                    //有网的时候读接口上的@Headers里的配置，你可以在这里进行统一的设置
                    String cacheControl = request.cacheControl().toString();
                    return response.newBuilder()
                            .header("Cache-Control", cacheControl)
                            .removeHeader("Pragma")
                            .build();
                } else {
                    int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
                    return response.newBuilder()
                            .header("Cache-Control", "public, only-if-cached, max-stale="+maxStale)
                            .removeHeader("Pragma")
                            .build();
                }

            }
        };
    }



    private class MyInterceptor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            HttpUrl.Builder authorizedUrlBuilder = request.url()
                    .newBuilder()
                    .scheme(request.url().scheme())
                    .host(request.url().host())
                    .addQueryParameter("ver", BaseUtil.getAppVersionName(MyApplication.context))
                    .addQueryParameter("ts",String.valueOf(System.currentTimeMillis()/1000));
            // 新的请求
            Request newRequest = request.newBuilder()
                    .method(request.method(), request.body())
                    .url(authorizedUrlBuilder.build())
                    .build();
            Response response = chain.proceed(newRequest);
            Log.d("retrofitRequest", String.format("receive Request--> %s on %s%n%s",
                    newRequest.url(), chain.connection(), newRequest.headers()));
            ResponseBody body = response.peekBody(1024 * 1024);
            String ss = body.string();
            Log.d("retrofitResponse", ss);

            return response;
        }

    }



    private static final Gson sGson = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd HH:mm:ss")
            .create();


    public  <S> S createOauthService(String baseUrl, Class<S> serviceClass) {
        Retrofit retrofit = new Retrofit.Builder()
                .client(sHttpClient)
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create(sGson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        return retrofit.create(serviceClass);

    }


    public  <S> S createNewService(Class<S> serviceClass) {
        if (TextUtils.isEmpty(OLD_API_BASE_URL)){
            return createOauthService(NEW_API_BASE_URL, serviceClass);
        }else {
            return createOauthService(OLD_API_BASE_URL, serviceClass);
        }

    }


}
